package pkg.commands;

import java.util.List;
import pkg.*;
import pkg.networking.NetworkedPlayer;
import pkg.networking.RemoteCommand;

public class PlayerExecutor implements ICommandExecutor {

	EntityManager entityManager;
	
	public PlayerExecutor(EntityManager entitys)
	{
		entityManager = entitys;
	}
	
	@Override
	public void setListener(ICommandExecListener listener) {
	}

	@Override
	public void execute(ICommand command) {
		if(!RemoteCommand.isRemoteCommand(command))
			return;
		
	    command = RemoteCommand.unpack(command);
		if(command instanceof PlayerCmd)
		{
			PlayerCmd cmd = (PlayerCmd) command;
			Player actualPlayer = getPlayer(cmd.getPlayerID());
			if(actualPlayer != null && actualPlayer instanceof NetworkedPlayer)
			{
				
			   cmd.setData((NetworkedPlayer)actualPlayer);
			   cmd.execute();
			   cmd.setData(null);//setData back to orignial state
			}
			else
				System.out.println("Error invalid player id came" +( actualPlayer instanceof NetworkedPlayer));
		}
		
	}
	
	private Player getPlayer(int id)
	{
		List<Entity> list = entityManager.getEntitys(EntityManager.Filters.withNetworkID(id));
		
		if(list == null || list.size() == 0)
			return null;
		else if(id < 0 || id >= list.size())
			return (Player)list.get(0);		
		else 
			return (Player)list.get(id);
	}

}
